package com.study.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.Constants.Constant;
import com.study.client.CompanyFeignClient;
import com.study.common.PageResult;
import com.study.common.Result;
import com.study.common.ResultCode;
import com.study.entity.company.Company;
import com.study.entity.system.User;
import com.study.service.UserService;
import com.study.util.poi.ExcelImportUtil;
import com.study.vo.system.ProfileResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wfw
 * @Date 2020/07/17 11:24
 */
@CrossOrigin
@RestController
@RequestMapping("sys/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private CompanyFeignClient companyFeignClient;

    @PostMapping("upload/{id}")
    public Result upload(@PathVariable String id , @RequestParam(name = "file") MultipartFile file){
        String imgUrl = userService.uploadImage(id, file);
        return new Result(ResultCode.SUCCESS, imgUrl);
    }

    /**
     * 导入Excel,添加用户
     */
    @PostMapping("import")
    public Result importUser(@RequestParam(name = "file") MultipartFile file) throws Exception {
        List<User> list = new ExcelImportUtil(User.class).readExcel(file.getInputStream(), 1, 1);
        //3.批量保存用户
        userService.saveAll(list , companyId , companyName);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 分配角色
     */
    @PutMapping("assignRoles")
    public Result save(@RequestBody Map<String,Object> map){

        // 获取被分配的用户id
        String userId = (String) map.get("id");
        //获取到角色的id列表
        List<String> roleIds = (List<String>) map.get("roleIds");
        // 调用service完成角色分配
        userService.assignRoles(userId , roleIds);

        return new Result(ResultCode.SUCCESS);
    }

    @PostMapping("")
    public Result save(@RequestBody User user){
        //设置保存的用户id
        user.setCompanyId(companyId);
        user.setCompanyName(companyName);
        //调用service完成保存用户
        userService.save(user);
        //构造返回结果
        return new Result(ResultCode.SUCCESS);
    }

    @GetMapping("")
    public Result findAll(int page, int size, @RequestParam() Map map){

        //获取当前的企业id
        map.put("companyId" , companyId);
        Page<User> pageUser = userService.findAll(map, page, size);
        //构造返回结果
        PageResult<User> pageResult = new PageResult<>(pageUser.getTotalElements(),pageUser.getContent());
        return new Result(ResultCode.SUCCESS , pageResult);
    }

    @GetMapping("{id}")
    public Result findById(@PathVariable(value = "id") String id){
        User user = userService.findById(id);
        return new Result(ResultCode.SUCCESS , user);
    }

    @PutMapping("{id}")
    public Result update(@PathVariable(value = "id") String id , @RequestBody User user){
        // 调用Service更新
        userService.update(id , user);
        return new Result(ResultCode.SUCCESS);
    }

    @RequiresPermissions(value = "API-USER-DELETE")
    @DeleteMapping(value = "{id}",name = "API-USER-DELETE")
    public Result delete(@PathVariable(value = "id") String id){
        userService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    @PostMapping("login")
    public Result login(@RequestBody Map<String, String> loginMap) {
        String mobile = loginMap.get("mobile");
        String password = loginMap.get("password");

        try {
            // 如果该公司被禁止登录,直接返回
            User user = userService.findByMobile(mobile);
            if (!Constant.UserLevelConstant.SAASADMIN.equals(user.getLevel())) {
                LinkedHashMap linkedHashMap = (LinkedHashMap) companyFeignClient.findCompanyById(user.getCompanyId()).getData();
                Company company = new ObjectMapper().readValue(new ObjectMapper().writeValueAsString(linkedHashMap), Company.class);
                if (!ObjectUtils.isEmpty(company)) {
                    if (Constant.CompanyConstant.COMPANY_DISABLE.equals(String.valueOf(company.getState()))) {
                        return new Result(ResultCode.UNAUTHORISE);
                    }
                }
            }
            // 构造登录令牌
            password = new Md5Hash(password, mobile, 3).toString();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(mobile, password);
            Subject subject = SecurityUtils.getSubject();
            // 调用login方法,进入realm完成认证
            subject.login(usernamePasswordToken);
            String sessionId = (String) subject.getSession().getId();
            return new Result(ResultCode.SUCCESS, sessionId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
        }
    }

    /**
     * 用户登录成功之后,获取用户信息
     */
    @PostMapping("profile")
    public Result profile(){
        // 获取session中的安全数据
        Subject subject = SecurityUtils.getSubject();
        // subject获取所有的安全集合
        PrincipalCollection principalCollection = subject.getPrincipals();
        // 获取安全数据
        ProfileResult result = (ProfileResult) principalCollection.getPrimaryPrincipal();

        return new Result(ResultCode.SUCCESS, result);
    }
}
